const fs = require("fs");
const { Schema } = require("mongoose");
const path = require("path");
const request = require("request");

const superagent = require("superagent");

function getPageData1() {
  console.log("执行 test 文件");
  request(
    {
      url: "https://api.bilibili.com/pgc/web/timeline?types=1&before=6&after=6",
      port: 80,
      method: "GET",
      headers: {
        // Host: "www.douban.com",
        Cookie: `bid=k0KKZrbo7XM; ll="118124"; douban-fav-remind=1; _pk_id.100001.8cb4=4b3dd85a56799805.1689584866.; _pk_ref.100001.8cb4=%5B%22%22%2C%22%22%2C1690859873%2C%22https%3A%2F%2Fwww.google.com%2F%22%5D; _pk_ses.100001.8cb4=1; __utma=30149280.56399573.1686458448.1689584786.1690859873.4; __utmc=30149280; __utmz=30149280.1690859873.4.4.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utmt=1; __utmb=30149280.2.10.1690859873`,
        "User-Agent":
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
      },
    },
    async (err, res, body) => {
      console.log(`STATUS: ${res.statusCode}`); //返回状态码
      console.log(`HEADERS: ${JSON.stringify(res.headers, null, 4)}`); // 返回头部
      res.setEncoding("utf8"); // 设置编码
      if (body) {
        // console.log(body);
        const htmlURL = path.resolve(__dirname, "../public/index.html");

        await fs.writeFileSync(htmlURL, ""); //清空文件
        const innerHTML = `<!DOCTYPE html>
              <html lang="en">
              <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Document</title>
              </head>
              <body>
                <script>
                  console.log(${body})
                </script>
              </body>
              </html>`;
        fs.writeFile(htmlURL, innerHTML, (err, data) => {
          if (err) {
            console.log("文件写入失败!");
            return;
          }
          console.log("文件写入成功~~~");
        });
      }
    }
  );

  // req.end();
}

function getPageData(mongoose) {
  // "https://api.bilibili.com/pgc/web/timeline?types=1&before=6&after=6"

  superagent
    .get("https://api.bilibili.com/pgc/web/timeline?types=1&before=6&after=6")
    .end(async (err, res) => {
      console.log(`STATUS: ${res.statusCode}`); //返回状态码
      console.log(`HEADERS: ${JSON.stringify(res.headers, null, 4)}`); // 返回头部
      // console.log(`BODY: ${res.text}`);
      const body = res.text;
      const result = body.result;
      // result
      const TimeLineModel = mongoose.model(
        "TimeLine",
        mongoose.Schema({
          date: String,
          date_ts: {
            type: Number,
            required: true,
            unique: true,
          },
          episodes: {
            type: [
              {
                cover: String,
              },
            ],
            default: undefined,
          },
          day_of_week: Number,
          is_today: Number,
        })
      );

      // TimeLineModel.deleteOne({
      //   date: "7-26",
      // }).then(({ deletedCount })=>{
      //   if(deletedCount){
      //     console.log("删除成功~~~")
      //   }else{
      //     console.log("删除失败~~~")
      //   }
      // })
      TimeLineModel.deleteMany({
        date: "7-26",
      }).then(({ deletedCount }) => {
        console.log(`批量删除${deletedCount}个`);
      });

      // TimeLineModel.create({
      //   date: "7-26",
      //   date_ts: 1690300800,
      //   episodes : [{
      //     cover : "自行车自行车自行车"
      //   }],
      //   day_of_week: 3,
      //   is_today: 0,
      // }).then((resp) => {
      //   console.log(resp);
      // });

      // const timeline = new TimeLineModel({
      //   date: "7-26",
      //   date_ts: 1690300800,
      //   day_of_week: 3,
      //   is_today: 0,
      // });
      // timeline.save().then((data)=>{
      //     console.log("插入成功~~~")
      // })

      return;
      [
        {
          date: "7-26",
          date_ts: 1690300800,
          day_of_week: 3,
          episodes: [
            {
              cover:
                "https://i0.hdslb.com/bfs/bangumi/image/cd224e3465166dc8a0ebec15265b64e2cfa19cec.jpg",
              delay: 0,
              delay_id: 0,
              delay_index: "",
              delay_reason: "",
              enable_vt: false,
              ep_cover:
                "http://i0.hdslb.com/bfs/archive/a0f14cccab3d3d3b593e0b685f1af47427d69baa.png",
              episode_id: 762946,
              follows: "-",
              plays: "-",
              pub_index: "第49话",
              pub_time: "00:00",
              pub_ts: 1690300800,
              published: 1,
              season_id: 45635,
              square_cover:
                "https://i0.hdslb.com/bfs/bangumi/image/9851386595b94be2e96955fb03584c959f1f11dd.jpg",
              title: "小猪佩奇 第九季 续集",
            },
          ],
          is_today: 0,
        },
      ];
      // fs.writeFile(htmlURL, innerHTML, (err, data) => {
      //   if (err) {
      //     console.log("文件写入失败!");
      //     return;
      //   }
      //   console.log("文件写入成功~~~");
      // });
    });
}

module.exports = {
  getPageData,
};
